package dao

import (
	"reflect"
	"team-evaluate/internal/model"
	"team-evaluate/pkg/app"
	"time"
)

func (d *Dao) CountUser() (int64, error) {
	var count int64
	if err := d.engine.Model(&model.User{}).Where("is_del = ?", 0).Count(&count).Error; err != nil {
		return 0, err
	}
	return count, nil
}

func (d *Dao) GetUserList(page, pageSize int) ([]*model.UserRes, error) {
	pageOffset := app.GetPageOffset(page, pageSize)
	var users []*model.UserRes
	var err error
	if pageOffset >= 0 && pageSize > 0 {
		d.engine = d.engine.Offset(pageOffset).Limit(pageSize)
	}
	if err = d.engine.Table("user").Where("is_del = ?", 0).Scan(&users).Error; err != nil {
		return nil, err
	}
	return users, nil
}

func (d *Dao) FindUserById(id uint32) (*model.UserRes, error) {
	user := model.UserRes{}
	var err error
	if err = d.engine.Table("user").Where("is_del = ? AND id = ?", 0, id).Scan(&user).Error; err != nil {
		return nil, err
	}
	return &user, nil
}

func (d *Dao) CreateUser(name string, email string, password string) error {
	user := model.User{
		Name:     name,
		Email:    email,
		Password: password,
	}
	return d.engine.Create(&user).Error
}

func (d *Dao) UpdateUser(updateUserValue *model.UpdateUserRequest) error {
	values := map[string]interface{}{}
	t := reflect.TypeOf(*updateUserValue)
	v := reflect.ValueOf(*updateUserValue)
	for k := 0; k < t.NumField(); k++ {
		//fmt.Printf("%s -- %v \n", t.Field(k).Name, v.Field(k).Interface())
		if t.Field(k).Name == "ID" {
			continue
		}
		if t.Field(k).Name == "Age" {
			if v.Field(k).Interface().(uint8) == 0 {
				continue
			}
		} else {
			if v.Field(k).Interface() == "" {
				continue
			}
		}
		jsonKey := t.Field(k).Tag.Get("json")
		values[jsonKey] = v.Field(k).Interface()
	}
	return d.engine.Model(&model.User{}).Where("id = ? AND is_del = ?", updateUserValue.ID, 0).Updates(values).Error
}

func (d *Dao) DeleteUser(id uint32) error {
	nowTime := time.Now().Unix() * 1000
	return d.engine.Exec("update user set is_del = ?, deleted_on = ? where id = ?", true, nowTime, id).Error
}

func (d *Dao) FindOneUser(param *model.User) (*model.User, error) {
	var user model.User
	err := d.engine.Where(param).First(&user).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}
